//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.ashlikun.keeplive.service

import android.annotation.SuppressLint
import android.app.job.JobInfo
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.app.job.JobService
import android.content.*
import android.content.pm.PackageManager
import android.os.Build
import android.os.Build.VERSION
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import com.ashlikun.keeplive.KeepLive
import com.ashlikun.keeplive.utils.ServiceUtils

/**
 * @author　　: 李坤
 * 创建时间: 2022/4/29 21:03
 * 邮箱　　：496546144@qq.com
 *
 *
 * 功能介绍：启动定时器，在定时器中启动本地服务和守护进程
 */
@RequiresApi(api = 21)
class JobHandlerService : JobService() {
    private val jobScheduler by lazy { this.getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler }
    val stopReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            KeepLive.loge("JobHandlerService 我接收了关闭通知")
            stop()
        }
    }

    companion object {
        var jobServicePeriodic = 60 * 1000L

        @SuppressLint("MissingPermission")
        fun schedule(context: Context) {
            if (VERSION.SDK_INT >= 21) {
                val jobScheduler = context.getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler
                jobScheduler!!.cancel(KeepLive.jobId)
                val builder = JobInfo.Builder(KeepLive.jobId, ComponentName(context, JobHandlerService::class.java))
                //用于一次性任务  表示任务在至少多长时间后执行，不能和setPeriodic 同时使用，否则报错
//                builder.setMinimumLatency(1 * 60 * 1000)
                //用于一次性任务 表示任务在某段时间后必须执行 ，不能和setPeriodic 同时使用，否则报错
//                builder.setOverrideDeadline(1 * 60 * 1000)
                //布尔值，表示任务是否需要在设备处于空闲状态时执行。
                builder.setRequiresDeviceIdle(false)
                // 需要在充电状态下运行
                builder.setRequiresCharging(true)

                //表示任务间隔多长时间执行一次
                builder.setPeriodic(jobServicePeriodic)
                //  设置等待多长时间执行，默认是10s，如果小于10s，按照10s算
//            builder.setBackoffCriteria((10 * 1000).toLong(), JobInfo.BACKOFF_POLICY_LINEAR)
                // 需要任何类型的网络连接
                builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                // 设备重启后重新调度
                if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.RECEIVE_BOOT_COMPLETED) == PackageManager.PERMISSION_GRANTED) {
                    builder.setPersisted(true)
                }
                jobScheduler!!.schedule(builder.build())
            }
        }
    }

    fun stop() {
        KeepLive.loge("JobHandlerService  stop")
        runCatching {
            jobScheduler?.cancel(KeepLive.jobId)
            if (VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                stopForeground(KeepLive.notificationId)
            }
            stopSelf()
        }
    }

    @SuppressLint("MissingPermission")
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        schedule(this)
        this.startService(this)
        KeepLive.loge("JobHandlerService  onStartCommand")
        KeepLive.registerReceiver(this, stopReceiver, IntentFilter().apply {
            addAction(KeepLive.RECEIVER_KEEP_STOP)
        })

        return START_STICKY
    }

    private fun startService(context: Context) {
        if (KeepLive.isStart) {
            KeepLive.loge("JobHandlerService  startService")
            //启用前台服务，提升优先级
            KeepLive.createNot(this)?.apply {
                startForeground(KeepLive.notificationId, build())
            }
            this.startService(Intent(context, LocalService::class.java))
            if (KeepLive.config.remoteEnable) this.startService(Intent(context, RemoteService::class.java))
        } else {
            if (KeepLive.config.isCheckStart) {
                stop()
            }
        }
    }

    // 当任务 被调度时调用
    override fun onStartJob(jobParameters: JobParameters?): Boolean {
        KeepLive.loge("JobHandlerService  onStartJob")
        if (!ServiceUtils.isServiceRunning(this.applicationContext, LocalService::class.java.name) || (KeepLive.config.remoteEnable && !ServiceUtils.isRunningTaskExist(
                this.applicationContext, this.packageName + ":remote"
            ))
        ) {
            this.startService(this)
        }
        return false
    }

    override fun onStopJob(jobParameters: JobParameters?): Boolean {
        KeepLive.loge("JobHandlerService  onStopJob")
        if (!ServiceUtils.isServiceRunning(this.applicationContext, LocalService::class.java.name) || (KeepLive.config.remoteEnable && !ServiceUtils.isRunningTaskExist(
                this.applicationContext, this.packageName + ":remote"
            ))
        ) {
            this.startService(this)
        }
        return false
    }

    override fun onDestroy() {
        super.onDestroy()
        KeepLive.loge("JobHandlerService  onDestroy")
        runCatching {
            unregisterReceiver(stopReceiver)
        }
    }
}